package com.dsbj.wx.api.service;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.wx.api.config.HttpsClientRequestFactory;
import com.dsbj.wx.api.utils.PropertyUtil;
import com.dsbj.wx.api.utils.strprocess.ObjectParse;
import com.dsbj.wx.api.utils.strprocess.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信ACCESS_TOKEN服务类。
 * tips: 该类保证accessToken是有效的,其他方法若需使用accessToken,直接从该类中获取即可。
 * @author cjw 2020-02-16
 */
@Service
@Transactional
public class WxAccessTokenService {
	
	public static Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);
	
	/**
	 * Map_AccessToken的格式为:《"accessToken", "expiresIn", "deadline"》。
	 */
	public static HashMap<String,Object> Map_AccessToken=new HashMap<>();
	
	@Resource(name = "httpsRestTemplate")
	private RestTemplate httpsRestTemplate;
	
	
	
	
	/**
	 * 从微信端获取accessToken,并存入Map_AccessToken。
	 *
	 * @param
	 * @return
	 * @author cjw 2020-02-16
	 */
	public ResponseMessage getWxAccessTokenFromWx(){
		String urlPattern="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
		String url=urlPattern.replace("APPID",PropertyUtil.getAppid()).replace("APPSECRET",PropertyUtil.getAppsecret());
		Map<String,Object> mapData=httpsRestTemplate.getForObject(url,Map.class);
		
		//若获取accessToken失败
		if(StrUtil.isEmpty(mapData.get("access_token"))){
			String mapDataStr="从微信端获取accessToken失败!"+StrUtil.tojsonstr(mapData);
			logger.error(mapDataStr);
			return ResponseMessage.error(mapDataStr);
		}
		
		//若成功获取
		Map_AccessToken.put("accessToken",mapData.get("access_token").toString());
		int expiresIn=ObjectParse.parse_toInt(mapData.get("expires_in"));
		long deadline=new Date().getTime()+expiresIn*1000;
		Map_AccessToken.put("expiresIn",expiresIn);
		Map_AccessToken.put("deadline",deadline);
		
		return ResponseMessage.ok();
	}
	
	
	
	
	
	/**
	 * 
	 * @param
	 * @return 
	 * @author cjw 2020-02-16
	 */
	public static void main(String[] args){
	
	}
	
}
